﻿using AppFramework.Configuration;
using AppFramework.Shared;
using AppFramework.Shared.Services.App;
using Prism.Regions;
using System; 
using System.Threading.Tasks;
using Prism.Ioc;
using AppFramework.Admin.Services;
using AppFramework.Shared.Services;
using Prism.Services.Dialogs;
using System.Windows;

namespace AppFramework.Admin.HandyUI
{
    internal class HandyUIStartService : IAppStartService
    {
        /// <summary>
        /// 创建窗口
        /// </summary>
        public void CreateShell()
        {
            var container = ContainerLocator.Container;

            //注入UserConfigurationService对象
            var userConfigurationService = container.Resolve<UserConfigurationService>(); 

            userConfigurationService.OnAccessTokenRefresh = OnAccessTokenRefresh; //委托赋值  令牌刷新处理
            userConfigurationService.OnSessionTimeOut = OnSessionTimeout;  //委托赋值  会话时间到期处理

            this.SplashScreenInitialized();

            //创建主窗口  
            var shell = container.Resolve<object>(AppViews.Main);  //主窗口
            if (shell is Window view)
            {
                //IRegionManager是Prism框架提供的区域管理功能（左侧边栏、页头，页尾，主内容区域）
                var regionManager = container.Resolve<IRegionManager>();
                RegionManager.SetRegionManager(view, regionManager);
                RegionManager.UpdateRegions();

                //通过Prism框架中的区域导航服务INavigationAware，进行页面之间的跳转
                if (view.DataContext is INavigationAware navigationAware)
                {
                    //区域的导航
                    navigationAware.OnNavigatedTo(null);
                    App.Current.MainWindow = view;
                }
            }
        }

        /// <summary>
        /// 启动画面
        /// </summary>
        private void SplashScreenInitialized()
        {
            var dialogService = ContainerLocator.Container.Resolve<IHostDialogService>();
            var result = dialogService.ShowWindow(AppViews.SplashScreen).Result; //显示蓝色的启动窗口

            if (result == ButtonResult.Ignore)
            {
                if (!Authorization()) Exit();
            }
            else if (result == ButtonResult.No) Exit();
        }

        /// <summary>
        /// 判断用户是否已登录
        /// </summary>
        /// <returns></returns>
        private bool Authorization()
        {
            var validationResult = Validation();
            if (validationResult == ButtonResult.Retry)
                return Authorization();

            return validationResult == ButtonResult.OK;

            static ButtonResult Validation()
            {
                var dialogService = ContainerLocator.Container.Resolve<IHostDialogService>();
                //如果登录就跳登录页面
                return dialogService.ShowWindow(AppViews.Login).Result; //显示登录页面
            }
        }

        public static async Task OnSessionTimeout()
        {
            await ContainerLocator.Container.Resolve<IAccountService>().LogoutAsync();
        }

        public static async Task OnAccessTokenRefresh(string newAccessToken)
        {
            await ContainerLocator.Container.Resolve<IAccountStorageService>().StoreAccessTokenAsync(newAccessToken);
        }

        /// <summary>
        /// 退出程序
        /// </summary>
        public void Exit()
        {
            if (System.Windows.Application.Current is IAppTaskBar appTaskBar)
                appTaskBar.Dispose();

            Environment.Exit(0);
        }

        public void Logout()
        {
            App.Current.MainWindow.Hide();
            SplashScreenInitialized();
            App.Current.MainWindow.Show();

            if (App.Current.MainWindow.DataContext is INavigationAware navigationAware)
                navigationAware.OnNavigatedTo(null);
        }
    }
}
